var http = require('http');
var urlUtils = require('url');
var fs = require('fs');

var querystring = require('querystring');

var app = http.createServer(function(req, res) {
	var urlObj = urlUtils.parse(req.url, true);
	var path = urlObj.pathname; //获得请求资源的路径
	switch (path) {
		case "/login":
			//读取登陆页面
			fs.readFile('./index.html', (err, data) => {
				if (err) throw err;
				res.write(data);
				res.end();
			})
			break;
		case "/user":
			var str = '';
			req.on('data', (chunk) => {
				str += chunk.toString();
			})
			req.on('end', () => {

				var params = querystring.parse(str);
				var users = require('./user.json');

				var flag = users.filter((user) => {
					return user.username === params.username && user.password === params.password;
				})
				if (flag.length) {
					res.write('welcome ' + flag[0].username);
				} else {
					res.write('username or password is wrong');
				}
				res.end();
			})
			break;
		default:
			console.log('404');
			break;
	}
})

app.listen(3000, function() {
	console.log('server start at 3000')
})